<script setup>
import { reactive } from 'vue'
import saleOrder from './saleOrder.vue'
import { getStockInfoBomAPI } from '@/api/warehouse/outbound/producfield.js'
const { proxy } = getCurrentInstance()
const props = defineProps({
  // 回显数据
  data: {
    type: Object,
    default: () => {}
  },
  //   判断
  title: {
    type: String,
    default: ''
  }
})

// 封装 方法 字典查询
const {
  plan_type // 计划类型
} = proxy.useDict('plan_type')

const emit = defineEmits(['cancel', 'submit'])

// 表单Ref
const ruleFormRef = ref(null)

// 新增字段
const ruleForm = reactive({ planType: '1', list: [] })

// 勾选要删除的
const selectTable = ref([])

/**
 * 状态参数
 */
const state = reactive({
  loading: false
})

const Code = ref('')

/**
 * 订单信息弹窗状态
 */
const saleOrderShow = ref(false)

/**
 * 物料信息弹窗状态-商品名称弹窗
 */
const materialShow = ref(false)

/**
 * +号弹窗
 */
const materialIsShow = ref(false)

/**
 * 客户信息弹窗状态
 */
const customerShow = ref(false)

/**
 * 监听回显
 */
watch(
  () => props.data,
  () => {
    if (props.data) {
      for (let key in props.data) {
        ruleForm[key] = props.data[key]
      }
    }
  },
  { deep: true, immediate: true }
)

/**
 * 表单校验
 */
const rules = reactive({
  planType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
  salesOrderNum: [{ required: true, message: '请选择订单单号', trigger: 'blur' }],
  planWeight: [{ required: true, message: '请输入订单数量', trigger: 'blur' }],
  materialName: [{ required: true, message: '请选择商品名称', trigger: 'blur' }],
  planStartWorkDate: [{ required: true, message: '请选择计划开工日期', trigger: 'blur' }],
  planEndWorkDate: [{ required: true, message: '请选择计划完工日期', trigger: 'blur' }]
})

/**
 * 订单信息弹窗入焦事件
 */
const salesFocus = () => {
  if (!ruleForm.planType) return proxy.warningMsg('请先选择计划类型！')
  saleOrderShow.value = true
}

/**
 * 物料信息弹窗入焦事件
 */
const materialFocus = () => {
  materialShow.value = true
}

/**
 * 客户信息弹窗入焦事件
 */
const customerNameFocus = () => {
  customerShow.value = true
}

/**
 * 订单单号弹窗确认
 */
const saleOrderSub = async val => {
  try {
    ruleForm.salesOrderNum = val.salesOrderNum
    ruleForm.customerNum = val.customerNum
    ruleForm.contractNumber = val.contractNumber
    //  // 计划类型为14时物料编码赋值
    ruleForm.materialCodeType1 = val.materialCode
    Code.value = val.materialCode
    ruleForm.materialCode = val.materialCode
    ruleForm.materialName = val.materialName
    ruleForm.customerName = val.customerName
    ruleForm.specType = val.specType
    ruleForm.planWeight = val.planWeight
    ruleForm.materialUnit = val.materialUnit
    ruleForm.deliveryDate = val.deliveryDate
    ruleForm.remark = val.remark
    saleOrderShow.value = false
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCodeType1,
      planWeight: ruleForm.planWeight
    })
    res.data.forEach(item => {
      ruleForm.list.push(item)
    })
  } catch (error) {}
}

/**
 * 商品名称选择确认
 */
const materialSub = val => {
  ruleForm.materialName = val.materialName
  // 计划类型为23时物料编码赋值
  ruleForm.materialCodType23 = val.materialCode
  Code.value = val.materialCode
  ruleForm.materialCode = val.materialCode
  ruleForm.specType = val.specType
  ruleForm.materialUnit = val.materialUnitDict
  materialShow.value = false
}

/**
 * 客户信息选择确认
 */
const customerChange = val => {
  ruleForm.customerName = val.customerName
  ruleForm.customerNum = val.customerNum

  ruleForm.customerId = val.id
  close()
}

const close = () => {
  customerShow.value = false
}

/**
 * 不能输入小数点
 * @param e
 * @param row
 */
const handleChangePackCount = (e, row) => {
  e = e.replace(/[^0-9]/g, '')
  ruleForm.planWeight = e
}

/**
 * 订单数量回车事件 计划类型为1
 */
const planWeightSubType1 = async () => {
  ruleForm.list = []
  try {
    if (!ruleForm.salesOrderNum) return proxy.warningMsg('请先选择订单单号!')
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCodeType1,
      planWeight: ruleForm.planWeight
    })
    // res.data.forEach(item => {
    //   ruleForm.list.push(item)
    // })
    ruleForm.list = res.data
  } catch (error) {}
}

/**
 * 订单数量回车事件 计划类型为23
 */
const planWeightSubType23 = async () => {
  ruleForm.list = []
  try {
    if (!ruleForm.materialName) return proxy.warningMsg('请先选择商品名称！')
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCodType23,
      planWeight: ruleForm.planWeight
    })
    // res.data.forEach((item) => {
    //   ruleForm.list.push(item);
    // });
    ruleForm.list = res.data
  } catch (error) {}
}

/**
 * +号弹窗表格添加
 */
const addTable = () => {
  materialIsShow.value = true
}

// +号弹窗物料选择
const materialIsShowSub = val => {
  val.list.forEach(item => {
    ruleForm.list.push({ ...item, flag: false, id: item.materialId })
  })

  materialIsShow.value = false
}

// 勾选列表数据
const handleSelectionChange = rows => {
  selectTable.value = rows
}

// 表格删除
const remove = () => {
  if (selectTable.value.length > 0) {
    selectTable.value.forEach(item => {
      const Find = ruleForm.list.findIndex(itemy => item.id == itemy.id)
      ruleForm.list.splice(Find, 1)
    })
  } else {
    ruleForm.list.splice(ruleForm.list.length - 1, 1)
  }
}

/**
 * 类型
 */
const isTypeList = async () => {
  ruleForm.list = []
  try {
    const res = await getStockInfoBomAPI({
      materialCode: Code.value,
      planWeight: ruleForm.planWeight,
      isTwoFlag: true
    })

    ruleForm.list = res.data
  } catch (error) {}
}

/**
 * 提交
 */
const submit = () => {
  return new Promise(async (resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.warningMsg('请填写完整')
        return
      }
      // if (ruleForm.list.length == 0) return proxy.warningMsg('请手动选择物料明细或者通过订单数量自动获取!')
      resolve(ruleForm)
    })
  })
}

/**
 * 事件抛出
 */
defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      inline
      ref="ruleFormRef"
      class="demo-ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      label-position="right"
      status-icon
    >
      <!-- 生产计划 -->
      <div v-if="ruleForm.planType == '1' || ruleForm.planType == '4'">
        <el-form-item label="计划类型" prop="planType">
          <p-select
            :option="plan_type"
            :disabled="props.title != '创建生产计划'"
            v-model="ruleForm.planType"
            placeholder="请选择计划类型"
          />
        </el-form-item>
        <el-form-item label="订单单号" prop="salesOrderNum">
          <el-input
            clearable
            :disabled="props.title != '创建生产计划'"
            v-model="ruleForm.salesOrderNum"
            @focus="salesFocus"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.materialName" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.customerName" />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.specType" />
        </el-form-item>
        <el-form-item label="订单数量" prop="planWeight">
          <el-input
            type="number"
            placeholder="请输入数量并回车"
            :min="0"
            autosize
            oninput="if(value<=0)value=''"
            @input="e => handleChangePackCount(e)"
            :disabled="props.title == '查看'"
            v-model="ruleForm.planWeight"
            @keyup.enter="planWeightSubType1"
          />
        </el-form-item>
        <el-form-item label="单位">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.materialUnit" />
        </el-form-item>
        <el-form-item label="交货日期">
          <el-date-picker
            clearable
            v-model="ruleForm.deliveryDate"
            type="date"
            :disabled="props.title == '查看' || props.title == '修改'"
            placeholder="请选择交货日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="计划开工日期" prop="planStartWorkDate">
          <el-date-picker
            clearable
            v-model="ruleForm.planStartWorkDate"
            type="date"
            :disabled="props.title == '查看'"
            placeholder="请选择计划开工日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="计划完工日期" prop="planEndWorkDate">
          <el-date-picker
            clearable
            v-model="ruleForm.planEndWorkDate"
            type="date"
            :disabled="props.title == '查看'"
            placeholder="请选择计划完工日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="rk">
          <el-form-item label="商品行备注">
            <el-input
              autosize
              clearable
              :disabled="props.title == '查看' || props.title == '审核计划' || props.title == '修改'"
              v-model="ruleForm.remark"
              :rows="4"
              type="textarea"
              placeholder=""
            />
          </el-form-item>
          <div class="rk" v-if="props.title == '审核计划'">
            <el-form-item label="审核意见" prop="auditOpinion">
              <el-input type="textarea" clearable v-model="ruleForm.auditOpinion" placeholder="请填写审核意见" />
            </el-form-item>
          </div>
        </div>
      </div>
      <!-- 备案计划 || 样品计划-->
      <div v-else>
        <el-form-item label="计划类型" prop="planType">
          <p-select
            :option="plan_type"
            :disabled="props.title != '创建生产计划'"
            v-model="ruleForm.planType"
            placeholder="请选择计划类型"
          />
        </el-form-item>
        <el-form-item label="订单单号">
          <el-input
            autosize
            clearable
            :disabled="props.title != '创建生产计划' || ruleForm.planType == '2' || ruleForm.planType == '3'"
            v-model="ruleForm.salesOrderNum"
            @focus="salesFocus"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="materialName">
          <el-input
            autosize
            clearable
            :disabled="props.title != '创建生产计划'"
            @focus="materialFocus"
            v-model="ruleForm.materialName"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            autosize
            clearable
            @focus="customerNameFocus"
            :disabled="props.title != '创建生产计划'"
            v-model="ruleForm.customerName"
          />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.specType" />
        </el-form-item>
        <el-form-item label="订单数量" prop="planWeight">
          <el-input
            type="number"
            placeholder="请输入数量并回车"
            @keyup.enter="planWeightSubType23"
            :min="0"
            autosize
            oninput="if(value<=0)value=''"
            @input="e => handleChangePackCount(e)"
            :disabled="props.title == '查看'"
            v-model="ruleForm.planWeight"
          />
        </el-form-item>
        <el-form-item label="单位">
          <el-input autosize clearable :disabled="props.title != '创建生产计划'" v-model="ruleForm.materialUnit" />
        </el-form-item>
        <el-form-item label="交货日期">
          <el-date-picker
            clearable
            v-model="ruleForm.deliveryDate"
            type="date"
            :disabled="props.title == '查看' || props.title == '修改'"
            placeholder="请选择交货日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="计划开工日期" prop="planStartWorkDate">
          <el-date-picker
            clearable
            v-model="ruleForm.planStartWorkDate"
            type="date"
            :disabled="props.title == '查看'"
            placeholder="请选择计划开工日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="计划完工日期" prop="planEndWorkDate">
          <el-date-picker
            clearable
            v-model="ruleForm.planEndWorkDate"
            type="date"
            :disabled="props.title == '查看'"
            placeholder="请选择计划完工日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="rk">
          <el-form-item label="商品行备注">
            <el-input
              autosize
              clearable
              :disabled="props.title == '查看' || props.title == '审核计划' || props.title == '修改'"
              v-model="ruleForm.remark"
              :rows="4"
              type="textarea"
              placeholder=""
            />
          </el-form-item>
          <div class="rk" v-if="props.title == '审核计划'">
            <el-form-item label="审核意见" prop="auditOpinion">
              <el-input type="textarea" clearable v-model="ruleForm.auditOpinion" placeholder="请填写审核意见" />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <p-table-add v-if="props.title == '创建生产计划'" title="物料明细" @add="addTable" @remove="remove" />
    <el-button type="warning" @click="isTypeList">类型</el-button>
    <el-table v-loading="state.loading" stripe border :data="ruleForm.list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column label="物料编码" prop="materialCode" width="220"> </el-table-column>
      <el-table-column label="物料名称" prop="materialName" width="180" />
      <el-table-column label="规格型号" prop="specType" width="220" />
      <el-table-column label="规格说明" prop="materialSpec" width="220" />
      <el-table-column label="类型" prop="type" width="220" />
      <el-table-column label="用量" prop="bomProportion" width="220" />
      <el-table-column label="位号" prop="bomBitNum" width="220" />
      <el-table-column label="类型" prop="type" width="220" />
      <el-table-column label="库存数量" prop="stockNum" width="120" />
      <el-table-column label="所需数量" align="center" width="220">
        <template #default="scope">
          <!--  @blur="isTableList(scope.row)"
            @input="e => handleChangePackCount(e, scope.row)" -->
          <el-input
            type="number"
            :disabled="props.title == '查看'"
            v-model="scope.row.plannedWeight"
            placeholder="请填写内容"
            oninput="if(value<=0)value=''"
          />
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="materialUnitDict" width="120" />
    </el-table>

    <saleOrder
      :bdb="true"
      :is-show="saleOrderShow"
      :type="ruleForm.planType"
      @preservation="saleOrderSub"
      @cancel="saleOrderShow = false"
    />

    <Material
      :is-show="materialShow"
      :dict="[
        {
          label: '原料',
          value: '1'
        },
        {
          label: '半成品',
          value: '3'
        },
        {
          label: '辅料',
          value: '2'
        },
        {
          label: '成品',
          value: '4'
        }
      ]"
      :bdb="true"
      @preservation="materialSub"
      @cancel="materialShow = false"
    />

    <!-- 物料选择 -->
    <Material
      :dict="[
        { label: '原料', value: '1' },
        { label: '半成品', value: '3' },
        { label: '辅料', value: '2' },
        { label: '成品', value: '4' }
      ]"
      :bdb="false"
      :is-show="materialIsShow"
      @preservation="materialIsShowSub"
      @cancel="materialIsShow = false"
    />

    <!-- 客户 -->
    <p-customer :is-show="customerShow" @preservation="customerChange" @cancel="customerShow = false" />
  </div>
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}
.btn {
  margin-top: 20px;
}
</style>
